#include <iostream>
#include<fstream>
#include <cstdlib>
#include <iterator>
#include <vector>
#include <string>
#include <memory>
#include <cstdlib>
#include <restbed>
#include <chrono>
#include <regex> 
//#include <time.h>
#include<ctime>
#include "tts_config.h"
#include "minilogger.h"
#include "dmnbtext.h"
using namespace std;
using namespace restbed;


/*
# curl http://192.168.12.103:1985/classifier/v1?text=%E6%88%91%E6%98%8E%E5%A4%A9%E8%BF%98
网页方式: http://192.168.12.103.1985/classifier/v1?text=我明天还
*/

extern TTSConfig config;
miniLogger<TextDecorator> logger;
DMNBText dmnbtext;

void get_classifier_handler(const shared_ptr< Session > session)
{
    clock_t tm4;
    stringstream id;
    id << ::this_thread::get_id();
    //cout << "thread id:" << id.str().data() << endl;
    string line_out = "[Classifer] WorkId=[ " + id.str()+" ] \n";
    const auto request = session->get_request();
   
    //-----------------------------------classifier----------------------------------
    string raw_txt = request->get_query_parameter("text");
    if (raw_txt.empty()){
        session->close(OK, "request text is null string or too long!", { { "Content-Length", "42" } });
        return;
    } 
    line_out += ("text="  + raw_txt + "\n");
    cout << line_out << endl;
    logger.Log(line_out);  

    string result = dmnbtext.predict(raw_txt);
    cout << result << endl;
    logger.Log(result);

    const multimap< string, string > headers
    {
        { "Content-Type", "text/plain;charset=utf-8" },
        { "Content-Length",to_string(result.size()) }
    };
            
    session->close(OK, result, headers);
}

void failed_filter_validation_handler(const shared_ptr< Session > session)
{
    session->close(400);
}

int main(const int argc, const char** argv)
{
    logger.InitLogFile(config.log_file, "TextClassifier!", true, true);
    string filename = argv[1];
  	dmnbtext.initClassifier(filename,false,20);
	dmnbtext.buildClassifier();
	
    auto resource = make_shared< Resource >();
    resource->set_path("/classifier/v1");
    resource->set_failed_filter_validation_handler(failed_filter_validation_handler);
    //resource->set_method_handler("GET", { { "Accept", "application/json" }, { "Content-Type", "application/json" } }, &get_json_method_handler);
    //resource->set_method_handler("GET",  &get_json_method_handler);
    resource->set_method_handler("GET",  &get_classifier_handler);

    auto settings = make_shared< Settings >();
    settings->set_bind_address(config.bind_address);
    settings->set_port(config.port);
    settings->set_worker_limit(config.worker_limit);
    settings->set_connection_limit(config.connection_limit);
    settings->set_connection_timeout(chrono::seconds(180));
    settings->set_default_header("Access-Control-Allow-Origin", "*");
    settings->set_default_header("Connection", "close");

    Service service;
    service.publish(resource);
    service.start(settings);

    return EXIT_SUCCESS;
}
